import logging
import os
import sys


class PackagePathFilter(logging.Filter):
    def filter(self, record):
        pathname = record.pathname
        record.relativepath = None
        root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        if pathname.startswith(root_path):
            record.relativepath = os.path.relpath(pathname, root_path)
        return True


# 创建日志记录器
log = logging.getLogger(__name__)

# 创建日志格式化器
formatter = logging.Formatter("%(relativepath)s:%(lineno)s %(asctime)s %(levelname)s - %(message)s")
# formatter = logging.Formatter("%(module)s:%(filename)s:%(lineno)s %(asctime)s %(levelname)s - %(message)s")

#创建日志处理程序
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
console_handler.addFilter(PackagePathFilter())

# 将处理程序添加到记录器
log.addHandler(console_handler)

# 设置记录器级别
log.setLevel(logging.DEBUG)
log.addFilter(PackagePathFilter())

# 获取所有已注册的日志记录器
loggers = logging.Logger.manager.loggerDict
log.debug(log.handlers)
# 给每个日志记录器添加过滤器
for logger in loggers.values():
    if isinstance(logger, logging.Logger):
        logger.addFilter(PackagePathFilter())

debug = log.debug
info = log.info
